package com.shcz.migu.ui.base;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.shcz.migu.R;
import com.shcz.migu.app.ActivityContainers;
import com.shcz.migu.app.App;
import com.shcz.migu.local_setting.LocalConstants;
import com.shcz.migu.presenter.base.BasePresenter;
import com.shcz.migu.presenter.base.BaseView;
import com.shcz.migu.ui.fragment.FailureFragment;
import com.shcz.migu.ui.fragment.LoadFragment;
import com.shcz.migu.utils.CommonToast;
import com.shcz.migu.utils.Constants;
import com.shcz.migu.utils.PhotoController;
import com.shcz.migu.utils.UserInforUtils;
import com.shcz.migu.widget.base.AutoHeightLayout;
import com.shcz.migu.widget.base.CTitleBar;
import com.shcz.migu.widget.base.statusbar.StatusBarUtil;

import butterknife.ButterKnife;


public abstract class BaseActivity<P extends BasePresenter> extends ShakeActivity
        implements InputMethodRelativeLayout.OnSizeChangedListener,
        BaseView, PhotoController.PhotoControllerListener {

    protected CTitleBar mTitleBar;
    public RelativeLayout contentView;
    protected AutoHeightLayout autoHeightView;
    private Fragment loadFragment, failureFragment;
    protected View mBottomView, mTopView;
    protected P mPresenter;
    public static final String BROADCAST_MSG_CLOSE_ACTIVITY = "com.cyjx.education.exit";

    private PhotoController photoController;
    protected boolean isNeedPhotoController = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            isCrop = savedInstanceState.getBoolean("isCrop");
            tempImagefilePath = savedInstanceState.getString(Constants.EXTRA_TEMP_IMAGE_PATH);
            cropImagefilePath = savedInstanceState.getString(Constants.EXTRA_CROP_IMAGE_PATH);
        }
        super.setContentView(R.layout.activity_base);
        CommonToast.init(this);

        ActivityContainers.getInstance().addActivity(this);
        initBaseViews();
        mPresenter = createPresenter();
        registerBoradcastReceiver();
    }

    protected void initGallary() {
        initGallaryController();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (isNeedPhotoController && photoController != null) {
            outState.putSerializable("isCrop", photoController.isCrop());
            outState.putString(Constants.EXTRA_TEMP_IMAGE_PATH, photoController.getTempImagefilePath());
            outState.putString(Constants.EXTRA_CROP_IMAGE_PATH, photoController.getCropImagefilePath());
        }
    }

    private void initBaseViews() {
        autoHeightView = (AutoHeightLayout) findViewById(R.id.auto_height_layout);
        mTitleBar = (CTitleBar) findViewById(R.id.c_titlebar);
        contentView = (RelativeLayout) findViewById(R.id.re_basecontent);
//        contentView.setOnSizeChangedListener(this);
        mTitleBar.setOnClickListener(new CTitleBar.OnTitleButtonClickListener() {
            @Override
            public void onTitleButtonClicked(int buttonType) {
                switch (buttonType) {
                    case CTitleBar.BUTTON_LEFT_ICON:
                        finish();
                        break;
                }
            }
        });
    }


    @Override
    public void setContentView(int layoutResID) {
        contentView.removeAllViews();
        getLayoutInflater().inflate(layoutResID, contentView, true);
        ButterKnife.bind(this);
        setupViews();
        setStatusBar();
    }

    protected P createPresenter() {
        return null;
    }

    public void cancel(View view) {
        finish();
    }

    protected abstract void setupViews();

    @Override
    protected void onPause() {
        super.onPause();


    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterBroadcastReceiver();
        if (mPresenter != null) {
            mPresenter.onDestroy();
        }
        mPresenter = null;
        ActivityContainers.getInstance().removeActivity(this);
    }

    protected void showToast(String msg) {
        CommonToast.showToast(msg);
    }

    protected void setStatusBar() {
        StatusBarUtil.setColor(this, getResources().getColor(R.color.title_bar_color), 0);
    }


    private String tempImagefilePath = "";
    private String cropImagefilePath = "";
    private boolean isCrop = false;


    private void initGallaryController() {
        photoController = new PhotoController(this);
        photoController.setPhotoControllerListener(this);
        photoController.setCrop(isCrop);
        photoController.setTempImagefilePath(tempImagefilePath);
        photoController.setCropImagefilePath(cropImagefilePath);
    }

    public void setCrop(boolean isCrop) {
        if (photoController != null)
            photoController.setCrop(isCrop);
    }

    public void setWithAspect(boolean isWithAspect) {
        if (photoController != null)
            photoController.setWithAspect(isWithAspect);
    }

    public void getPhotoFromAlbum() {
        if (photoController != null)
            photoController.getPhotoFromAlbum();
    }

    public void getPhotoFromCamera() {
        if (photoController != null)
            photoController.getPhotoFromCamera();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (photoController != null)
            photoController.onActivityResult(requestCode, resultCode, intent);
    }

    @Override
    public void onGetPhoto(String path) {
    }

    protected void hideSoftInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
    }


    /***************关于标题的设置*************************/
    public void setTitle(int stringid) {
        setTitle(getString(stringid));
    }

    public void setTitle(int stringid, int color) {
        setTitle(getString(stringid), getResources().getColor(color));
    }

    public void setTitle(String string, int color) {
        setTitle(string);
        mTitleBar.setTitleTextColor(color);
    }

    public void setTitle(String string) {
        if (string != null) mTitleBar.setTitle(string);
    }

    public void setTitleRightText(String string, int color, View.OnClickListener listener) {
        mTitleBar.setTitleRightText(string, color, listener);
    }

    public void setTitleRightText(String string) {
        mTitleBar.setTitleRightText(string);
    }

    public void setTitleRightText(String string, View.OnClickListener listener) {
        mTitleBar.setTitleRightText(string, listener);
    }

    public void setTitleLeftText(String string, int color, View.OnClickListener listener) {
        mTitleBar.setTitleLeftText(string, color, listener);
    }

    public void setTitleLeftImgButtonVisible(int visibility) {
        mTitleBar.setTitleLeftButtonVisibility(visibility);
    }

    public void setTitleLeftButton(int resId, View.OnClickListener listener) {
        mTitleBar.setTitleLeftButton(resId, listener);
    }

    public void setTitleLeftButton(View.OnClickListener listener) {
        mTitleBar.setTitleLeftButton(listener);
    }

    public void setTitleRightButton(int resId, View.OnClickListener listener) {
        mTitleBar.setTitleRightButton(resId, listener);
    }


    public void setTitleBarDividerVisibility(int visibility) {
        mTitleBar.setTitleBarDividerVisibility(visibility);
    }

    /**
     * 设置titleBar的背景颜色
     *
     * @param color color
     */
    public void setTitleBackgroundColor(int color) {
        findViewById(R.id.main_view).setBackgroundColor(color);
    }

    public void setNoTitle() {
        mTitleBar.setVisibility(View.GONE);
    }

    public void setHasTitle() {
        mTitleBar.setVisibility(View.VISIBLE);
    }

    @Override
    public void onSizeChange(boolean flag, int listHeight, int inputViewHeight) {
        if (flag) {
            int deviceHeight = App.getDisplayMetrics(this).heightPixels;
            Rect r = new Rect();
            View rootview = this.getWindow().getDecorView();
            rootview.getWindowVisibleDisplayFrame(r);
//            contentView.setPadding(0, -(deviceHeight - r.bottom), 0, 0);
        } else {
            contentView.setPadding(0, 0, 0, 0);
        }
    }

    /**
     * View的状态
     */
    protected final static int View_State_Loadding = 0;
    protected final static int View_State_Normal = 1;
    protected final static int View_State_Fail = 2;
    protected final static int View_State_Empty = 3;
    protected final static int View_State_GONE = 4;

    protected void setViewState(int state) {
        switch (state) {
            case View_State_Loadding:
                setStateLoad();
                break;
            case View_State_Empty:
                setStateFailOrEmpty();
                break;
            case View_State_Fail:
                setStateFailOrEmpty(R.mipmap.net_stable, R.string.network_failed, 0);
                break;
            case View_State_Normal:
            case View_State_GONE:
                setStateNormal();
                break;
        }
    }


    /**
     * 设置界面为Loadding
     */
    protected void setStateLoad() {
        if (loadFragment == null) {
            loadFragment = new LoadFragment();
        }
        if (!loadFragment.isAdded())
            setFragment(loadFragment);
    }

    /**
     * 设置界面为失败或者空，使用默认的icon和content，没有Button
     */
    protected void setStateFailOrEmpty() {
        if (failureFragment == null) {
            failureFragment = new FailureFragment();
        }
        setFragment(failureFragment);
    }

    /**
     * 设置界面为失败或者空 默认图片：iconResId == 0，图片空：iconResId == -1；
     *
     * @param iconResId    icon
     * @param contentResId content string id
     * @param btnResId     btn string id
     */
    protected void setStateFailOrEmpty(int iconResId, int contentResId, int btnResId) {
        setStateFailOrEmpty(iconResId, getString(contentResId), btnResId);
    }


    /**
     * 设置界面为失败或者空 默认图片：iconResId == 0，图片空：iconResId == -1；
     *
     * @param iconResId icon
     * @param content   string
     */
    protected void setStateFailOrEmpty(int iconResId, String content, int btnResId) {
        if (failureFragment == null) {
            failureFragment = new FailureFragment();
        }

        if (!failureFragment.isAdded()) {
            Bundle bundle = new Bundle();
            bundle.putInt(FailureFragment.ARGUMENT_ICON_ID, iconResId);
            bundle.putString(FailureFragment.ARGUMENT_CONTENT, content);
            bundle.putInt(FailureFragment.ARGUMENT_BUTTON, btnResId);
            failureFragment.setArguments(bundle);

            setFragment(failureFragment);
        }

    }

    /**
     * 设置界面为正常，会隐藏Loadding，应该在Load之后调用
     */
    protected void setStateNormal() {
        if (loadFragment != null) {
            removeFragment(loadFragment);
        }

        if (failureFragment != null) {
            removeFragment(failureFragment);
        }
    }

    /**
     * 设置Fragment，显示在Content中
     *
     * @param fragment fragment
     */
    protected void setFragment(Fragment fragment) {
        if (!this.isFinishing()) {
            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction transaction = fm.beginTransaction();
            transaction.replace(R.id.re_basecontent, fragment);
            transaction.commitAllowingStateLoss();
        }
    }

    /**
     * 设置Fragment，显示在Content中
     *
     * @param fragment fragment
     */
    protected void addFragment(int layoutId, Fragment fragment) {
        if (!this.isFinishing()) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            if (!fragment.isAdded()) {
                fragmentTransaction.add(layoutId, fragment);
            } else {
                fragmentTransaction.show(fragment);
            }
            fragmentTransaction.commitAllowingStateLoss();
        }
    }

    /**
     * 去除Fragment显示
     *
     * @param fragment fragment
     */
    protected void removeFragment(Fragment fragment) {
        if (!this.isFinishing()) {
            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction transaction = fm.beginTransaction();
            transaction.remove(fragment);
            transaction.commitAllowingStateLoss();
        }
    }


    @Override
    public void showNetWorkError() {

        CommonToast.showToast(getString(R.string.network_failed));
    }

    @Override
    public void showErrorMessage(String message) {
        if (message.contains(LocalConstants.NETWORK_FLAG)) {
            setViewState(View_State_Fail);
            CommonToast.showToast(R.string.net_work_error_msg);
        } else
            CommonToast.showToast(message);
    }

    @Override
    public void showLoadingView() {
        setViewState(View_State_Loadding);
    }

    @Override
    public void hideLoadingView() {
        setViewState(View_State_Normal);
    }

    @Override
    public void showEmptyView(int iconResId, int contentResId, int btnResId) {
        setStateFailOrEmpty(iconResId, contentResId, btnResId);
    }

    @Override
    public void showLoadingDialog(String msg) {
        showLoading(msg);
    }

    @Override
    public void hideLoadingDialog() {
        dismissLoading();
    }

    protected ProgressDialog mLoadingDialog;

    protected void showLoading(String msg) {
        if (mLoadingDialog == null) {
            mLoadingDialog = new ProgressDialog(this);
            mLoadingDialog.setIndeterminate(true);
        }
        if (TextUtils.isEmpty(msg))
            mLoadingDialog.setMessage(getString(R.string.loading));
        else
            mLoadingDialog.setMessage(msg);
        mLoadingDialog.show();
    }

    protected void dismissLoading() {
        if (mLoadingDialog != null) {
            mLoadingDialog.dismiss();
        }
    }

    private BroadcastReceiver mBroadcastReceiver;

    private void registerBoradcastReceiver() {
        mBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                finish();
            }
        };

        IntentFilter filter = new IntentFilter();
        filter.addAction(BROADCAST_MSG_CLOSE_ACTIVITY);
        LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, filter);
    }

    private void unregisterBroadcastReceiver() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
    }

    protected int getWidth() {
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        getWindow().setGravity(Gravity.BOTTOM);
        return dm.widthPixels;
    }


    protected void onExit() {
        UserInforUtils.clearData();
        ActivityContainers.getInstance().finishAllActivity();
    }

    public void ToastUtils(String text) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    }


}
